/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/longest-univalue-path
   @Language: C++
   @Datetime: 19-05-14 11:30
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	int dfs(TreeNode *root, int &path){
		int left=root->left?dfs(root->left,path):0;
		left=root->left && root->val==root->left->val ? left+1:0;
		int right=root->right?dfs(root->right,path):0;
		right=root->right&&root->val==root->right->val? right+1:0;
		path=max(path,left+right);
		return max(left,right);
	}
public:
	/**
	 * @param root: 
	 * @return: the length of the longest path where each node in the path has the same value
	 */
	int longestUnivaluePath(TreeNode * root) {
		// Write your code here
		int path=0;
		if(root) dfs(root,path);
		return path;
	}
};
